

jQuery(function ($) {
    var result;
    var addrs;
    var user = JSON.parse(localStorage.getItem('user_info')) || {};
    var id = user.id;
    var selected_goods = [];
    var userCity;
    var userDistrict;
    var userLocation;
    var userPhone;
    var userProvince;
    var userReceiver;
    var userStreet;
    var max_point = 0;
    if (id) {
        var userPoint = 0;
        renderAddressGrouping();
        getTotalPrice(userPoint);
        // sendCoupon();
    } else {
        //无用户提交订单
        $('.yc_pay').hide();
        var goodsList = JSON.parse(localStorage.getItem('noUsers')) || [];
        if (goodsList.length) {
            var html = '';
            var price = 0;
            for (var i = 0; i < goodsList.length; i++) {
                if (goodsList[i].selected_flag) {
                    if (goodsList[i].promotion_flag == 1) {
                        price += goodsList[i].promotion_price;
                    } else {
                        price += goodsList[i].goods_price;
                    }

                    html += '<li class="item clearfix" data-goods-id=' + goodsList[i].id + ('>\n                            <div class="clearfix">\n                                <div class="goods_pic">\n                                    <a target="_blank" href="/goods-' + goodsList[i].id + '.html"><img src="') + isImgHttp(goodsList[i].GoodsImgs.thumb) + ('" alt=""></a>\n                                </div>\n                                <div class="goods_content">\n                                    <div>\n                                        <a target="_blank" href="/goods-'+ goodsList[i].id + '.html">\n') + goodsList[i].name + '\n                                        </a>\n                                    </div>\n                                    <div class="goods_price">\n                                        <span>\uFFE5 ' + (goodsList[i].promotion_flag == 1 ? goodsList[i].promotion_price : goodsList[i].goods_price) + '</span>\n                                    </div>\n                                </div>\n                            </div>\n                    </li> ';
                }
            };
            $('.list').html(html);
            $('.amount_payable_m').html('￥' + keepTwoDecimalFull(price));
        } else {
            return;
        };
        var shopAddress = JSON.parse(localStorage.getItem('address'));

        if (!shopAddress) {
            $("#dialog").dialog({
                // width:690,
                modal: true
            });
        } else {
            joint_address(shopAddress.UserAddress);
        }
    }
    function getTotalPrice(userPoint) {
        var param = {
            "user_id": id,
            "point": userPoint
        };
        send_ajax('post', '/api/cart/amt', param, function callback(data) {
            if (data.code == 200) {
                var user = JSON.parse(localStorage.getItem('user_info')) || {};
                var point = user.point;
                  //目前拥有多少个畜牧币
                $('.have_integral').html(point);
                var cost_point = function cost_point(points) {
                    $('.input_number').bind('input propertychange', function () {
                        $(this).val($(this).val().replace(/\D/g, ''));
                        if (parseInt($(this).val()) > points) {
                            swal({
                                text: "您最多只能使用" + points + "个畜牧币",
                                type: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#bb696a',
                                cancelButtonColor: '#EEE',
                                confirmButtonText: '确定',
                                cancelButtonText: '取消'
                            });

                            $(this).val("");
                        } else {
                        }
                    });
                };

                max_point = data.data.maxPoint;
                $('.amount_payable_m').html('￥' + keepTwoDecimalFull(data.data.totalSum - data.data.discountAmt-data.data.discountPointAmt));
                $('.get_point').html(data.data.sendPoint);
                //最多使用多少畜牧币
                if (point < max_point) {
                    $('.max_point').html(point);
                    cost_point(point);
                } else {
                    $('.max_point').html(max_point);
                    cost_point(max_point);
                };
            }
        });
    };
    $(".input_number").blur(function(){
        var use_point;
        if($(this).val()==''){
            use_point=0
        }else{
            use_point= parseInt($(this).val());
        }
        getTotalPrice(use_point)
    });
    function renderAddressGrouping() {
        // $('.send_address').html('');
        selected_goods = [];
        var param = {
            '[]': {
                'Cart': {
                    'user_id': id
                },
                'Goods': {
                    'id@': '/Cart/goods_id'
                },
                'GoodsImgs': {
                    'main_flag': 1,
                    'goods_id@': '/Cart/goods_id'
                },
                'Activity': {
                    'id@': '/Cart/activity_id'
                },
                'ActivityDerate': {
                    'activity_id@': '/Activity/id'
                },
                'ActivityGift': {
                    'activity_id@': '/Activity/id'
                },
                'ActivityGiftGoods': {
                    'activity_gift_id@': '/ActivityGift/id',
                    'goods_id@': '/Cart/goods_id'
                },
                'ActivityVirtual': {
                    'activity_id@': '/Activity/id'
                },
                'ActivityVirtualCoupon': {
                    'virtual_id@': '/ActivityVirtual/id'
                },
                'Coupon': {
                    'id@': '/ActivityVirtualCoupon/coupon_id'
                }
            }
        };
        if (id) {
            var selectedGoods = [];
            var selectedGoodsIndex = 0;
            send_ajax('post', '/get', param, function callback(data) {
                if (data.code == 200) {
                    result = data["[]"];
                }
                //选中的商品
                for (var _i3 = 0; _i3 < result.length; _i3++) {
                    if (result[_i3].Goods) {
                        if (result[_i3].Cart) {
                            if (result[_i3].Cart.selected_flag == true) {
                                selectedGoods.push(result[_i3]);
                            }
                        }
                    }
                };
                var goodsIdArr=[];
                for (var k = 0; k < selectedGoods.length; k++) {
                    goodsIdArr.push(selectedGoods[k].Goods.id)

                };
                var param = {
                    user_id: id ? id : 0,
                    goodsIdList: goodsIdArr.join(',')
                };
                send_ajax('get', '/api/goods/status', param, function callback(res) {
                    if(res.code==200&& res.data){
                        var result = res.data;
                        for(var i = 0;i<selectedGoods.length;i++){
                            var a_goods = selectedGoods[i];
                            var goodsId = a_goods.Goods.id;
                            if(result[goodsId]!= undefined){
                               selectedGoods[i].Goods.goods_price = result[goodsId].price; 
                            }
                            selected_goods.push(selectedGoods[i]);

                        }
                        // coupon();
                        renderGoods();
                        
                    }
                   
                });
              
            });
        }
        //购物地址/有没有地址
    }
    //渲染商品
    function renderGoods() {
        var addressList = {
            "UserAddress[]": {
                "UserAddress": {
                    "user_id": id
                    //  "default_flag":1

                    //购物车列表
                } } };
        send_ajax('post', '/get', addressList, function callback(data) {
            var addrsIdArr = [];
            var isaddr_html = "";
            if (data.code == 200) {
                addrs = data["UserAddress[]"]; //沒有默認地址/
                if (addrs != undefined) {
                    for (var i = 0; i < addrs.length; i++) {
                        joint_address(addrs[i]);
                    }
                    if (addrs) {
                        var shopAddress = $('.addr .list');
                        for (var l = 0; l < selected_goods.length; l++) {
                                if (selected_goods[l].Goods) {
                                    $('.addr .list').append('<li class="item clearfix" data-cart-id=' + selected_goods[l].Cart.id + '>\n                                        <div class="clearfix">\n                                            <div class="goods_pic">\n                                                <a target="_blank" href="/goods-' + selected_goods[l].Goods.id + '.html"><img src="' + isImgHttp(selected_goods[l].GoodsImgs.thumb) + '" alt=""></a>\n                                            </div>\n                                            <div class="goods_content">\n                                                <div>\n                                                    <a target="_blank" href="/goods-' + selected_goods[l].Goods.id + '.html">\n                                                    ' + selected_goods[l].Goods.name + '\n                                                    </a>\n                                                </div>\n                                                <div class="goods_price">\n                                                    <span>\uFFE5' + keepTwoDecimalFull(selected_goods[l].Goods.goods_price) + '</span>\n                                                </div>\n                                            </div>\n                                        </div>\n                                    </li>');  
                                }
                            
                        };
                    };
                } else {
                    //没有地址的情况下
                    $('.send_address_top').append('<button class="add_address">您还没有注册地址，请点击注册!</button>');
                    $('.send_address').append('<div class="addr">\n                                                                <div class="send_goods_list clearfix">\n                                                                    <div class="send_goods">\n                                                                        <span> \u9001\u8D27\u6E05\u5355</span>\n                                                                    </div>\n                                                                </div>\n                                                                <ul class="list clearfix">\n                                                                </ul>\n                                                        </div>');

                    for (var m = 0; m < selected_goods.length; m++) {
                        isaddr_html += '<li class="item clearfix">\n                                            <div class="clearfix">\n                                                <div class="goods_pic">\n                                                    <a href="/goods-' + selected_goods[m].Goods.id + '.html" target="_blank">\n                                                    <img src="' + isImgHttp(selected_goods[m].GoodsImgs.thumb) + '" alt="' + selected_goods[m].Goods.name + '"></a>\n                                                </div>\n                                                <div class="goods_content">\n                                                    <div>\n                                                        <a>\n                                                        ' + selected_goods[m].Goods.name + '\n                                                        </a>\n                                                    </div>\n                                                    <div class="goods_price">\n                                                        <span>\uFFE5' + keepTwoDecimalFull(selected_goods[m].Goods.promotion_flag == 0 ? selected_goods[m].Goods.goods_price : selected_goods[m].Goods.promotion_price) + '</span>\n                                                    </div>\n                                                </div>\n                                            </div>\n                                        </li>';
                    };

                    $('.list').html(isaddr_html);
                }
            };

           
        });
    }
    //拼接购物地址
    function joint_address(address) {
            var area_ids = {
                "Area[]": {
                    "count": 10,
                    "Area": {
                        "use_flag": 1,
                        "id{}": [address.province, address.city, address.district, address.street]
                    }
                }
            };
            send_ajax('post', '/get', area_ids, function callback(data) {
                if (data.code == 200 && data["Area[]"]) {
                    //修改主数据
                    var addr_info = data["Area[]"];
                    address.province_obj = addr_info[0];
                    address.city_obj = addr_info[1];
                    address.district_obj = addr_info[2];
                    address.street_obj = addr_info[3];
                    if(address.default_flag==1){
                        userCity = address.city;
                        userDistrict = address.district;
                        userLocation = address.location;
                        userPhone = address.phone;
                        userProvince = address.province;
                        userReceiver = address.receiver;
                        userStreet = address.street;
                        $('.send_address_top').html('<p class="getAddrParam" data-address_id="'+address.id+'">' + address.receiver + "&nbsp" + address.phone + '</p>\n                        <p>' + (address.province_obj?address.province_obj.name:'') + "&nbsp" + (address.city_obj?address.city_obj.name:'') + "&nbsp" + (address.district_obj != undefined ? address.district_obj.name : '') + "&nbsp" + (address.street_obj != undefined ? address.street_obj.name : '') + "&nbsp" + address.location + '</p> ');
                    }
                }
            }); 

    };
    //渲染弹窗的地址
    function renderAddress(addr){
        var addrHtml = "";
        for (var i = 0; i < addr.length; i++) {
            addrHtml += '<li class="address_item" data-id=' + addr[i].id + '>\n                            <p>\n                                \u59D3\u540D\uFF1A' + addr[i].receiver + '\n                            </p>\n                             <p>\n                                \u7535\u8BDD: ' + addr[i].phone + '\n                            </p>\n                            <p>\n                               \u5730\u5740: ' + (addr[i].province_obj?addr[i].province_obj.name:'') + (addr[i].city_obj?addr[i].city_obj.name:'') + (addr[i].district_obj ? addr[i].district_obj.name : '') + addr[i].location + '\n                            </p>\n                            <p class="use_address">\n                                \u4F7F\u7528\u6B64\u5730\u5740\n                            </p>\n                        </li>';
        };
        $('.address_list').html(addrHtml);
        //使用此地址
        $('.use_address').click(function () {
            var address_id = $(this).parents('li').attr('data-id');
            var addrsInformation = addr.filter(function (el) {
                return el.id == address_id;
            });
            for (var j = 0; j < addrsInformation.length; j++) {
                var a_addr =addrsInformation[j];
                userCity = a_addr.city;
                userDistrict = a_addr.district;
                userLocation = a_addr.location;
                userPhone = a_addr.phone;
                userProvince = a_addr.province;
                userReceiver = a_addr.receiver;
                userStreet = a_addr.street;
                $('.send_address_top').html('<p class="getAddrParam" data-address_id="'+a_addr.id+'">' + a_addr.receiver + "&nbsp" + a_addr.phone + '</p>\n            <p>' + (a_addr.province_obj?a_addr.province_obj.name:'') + "&nbsp" + (a_addr.city_obj?a_addr.city_obj.name:'') + "&nbsp" + (a_addr.district_obj?a_addr.district_obj.name:'') + "&nbsp" + (a_addr.location?a_addr.location:'') + '</p> ');
            }
            $(this).parents('.change_address').removeClass('open');
        });
    };
    //使用其他地址切换
    if(id){
         $(document).on('click', '.other_address', function () {
        if ($('.change_address').hasClass('open')) {
            $('.change_address').removeClass('open');
        } else {
            $('.change_address').removeClass('open');
            $('.change_address').addClass('open');
        }

        var address_id = parseInt($(this).parents('.addr').attr('data-address_id'));

        // var addrsInformation = addrs.filter(function (el) {
        //     return el.id !== address_id;
        // });
        renderAddress(addrs);
        }); 
    }else{
         //修改地址
        $(document).on('click', '.modify_addres', function () {
            if (!shopAddress) {
                $("#dialog").dialog({
                    // width:690,
                    modal: true
                });
                return;
            }
            var addrClick = shopAddress.UserAddress;
            province_id = addrClick.province;
            city_id = addrClick.city;
            area_id = addrClick.district;
            town_id = addrClick.street;
            var city = addrClick.city_obj.name; //市
            var district = addrClick.district_obj.name;
            var province = addrClick.province_obj.name; //省
            if (addrClick.street_obj != undefined) {
                var street = addrClick.street_obj.name; //街道
                $('.town').show().removeAttr('disabled');;
            } else {
                var street = ""; //街道
                $('.town').hide();
            };
            var location = addrClick.location; //具体位置
            var receiver = addrClick.receiver; //接受者
            var phone = addrClick.phone; //电话
            $("#dialog").dialog({
                // width:690,
                modal: true
            });
            var option_province = document.querySelector('.province option');
            var option_city = document.querySelector('.city option');
            var option_area = document.querySelector('.area option');
            var option_town = document.querySelector('.town option');
            // $('.province').val(addrClick.province-1);
            $('.city').show().removeAttr('disabled');
            $('.area').show().removeAttr('disabled');
            $(option_province).text(province);
            $(option_city).text(city);
            $(option_area).text(district);
            $(option_town).text(street);
            $(option_province).val(addrClick.province);
            $(option_city).val(addrClick.city);
            $(option_area).val(addrClick.district);
            $(option_town).val(addrClick.street);
            $('.receiver').val(receiver);
            $('.detailed_txt').val(location);
            $('.phone').val(phone);
        });
    }
   
    $(document).on('click', '.add_address', function () {
        $('.change_address').hide();
        $("#dialog").dialog({
            // width:690,
            modal: true
        });
    });
    //关闭地址弹窗
    $('.cancel_address').click(function () {
        $("#dialog").dialog('close');
    });

    //选择付款的方式
    $('.pay_way a').click(function () {
        $('.payment_m').removeClass('open');
        $(this).find('.payment_m').addClass('open');
    });
    // var reg = /^1[3456789]\d{9}$/; //手机号码
    var reg = /[0-9]{6,20}/; //手机号码
    //保存收货地址
    var province_id = '';
    var city_id = '';
    var area_id = '';
    var town_id = '';
    $('.save_information').click(function () {
        var province = $('.province').val();
        var city = $('.city').val();
        var area = $('.area').val();
        var town = $('.town').val();
        var receiver = $('.receiver').val();
        var detailed_txt = $('.detailed_txt ').val();
        var phone = $.trim($(".phone").val());
        var mailbox = $.trim($(".mailbox").val());
        var fixedPhone = $.trim($(".fixedPhone").val());
        //非空验证
        if (receiver == "") {
            $('.receiver_msg').show();
            $('.receiver_msg').html('请您填写收货人姓名');
        } else {
            $('.receiver_msg').hide();
        }
        if (detailed_txt == "") {
            $('.detailed_msg').show();
            $('.detailed_msg').html('请您填写收货人详细地址');
        } else {
            $('.detailed_msg').hide();
        }
        //手机号码
        if (phone == "") {
            $('.phone_msg').show();
            $('.phone_msg').html('请您填写收货人手机号码');
        } else if (reg.test(phone)) {
            $('.phone_msg').hide();
        } else {
            $('.phone_msg').show();
            $('.phone_msg').html('手机号格式不对，请重新输入');
        }
        //保存收货地址
        var flag;
        if ($('.checkbox').is(':checked')) {
            flag = 1;
        } else {
            flag = 0;
        };
        if (province != '' && city != '' && area != '' && detailed_txt != '' && receiver != '' && phone != '') {
            $('.localInfo').hide();
            if (!isLinkage) {
                var params = {
                    "UserAddress": {
                        "city": city_id,
                        "default_flag": flag,
                        "district": area_id,
                        "location": detailed_txt,
                        "phone": phone,
                        "province": province_id,
                        "receiver": receiver,
                        "street": town_id,
                        "user_id": id
                    },
                    "TAG": "UserAddress"
                };
            } else {
                var params = {
                    "UserAddress": {
                        "city": cityId,
                        "default_flag": flag,
                        "district": areaId,
                        "location": detailed_txt,
                        "phone": phone,
                        "province": provinceId,
                        "receiver": receiver,
                        "street": townId,
                        "user_id": id
                    },
                    "TAG": "UserAddress"
                };
            }

            if (id) {
                send_ajax('post', '/post', params, function callback(result) {
                    if (result.code == 200) {
                        // window.location.reload(); //刷新当前页面
                        renderAddressGrouping();
                        $("#dialog").dialog('close');
                    }
                });
            } else {
                localStorage.setItem("address", JSON.stringify(params));
                window.location.reload();
                $("#dialog").dialog('close');
            }
        } else {
            $('.localInfo').show();
            $('.localInfo').html('请您填写完整的地区信息');
        }
    });
    //优惠券的选择
    function coupon() {
        var tempDate = []; //调教订单商品数据
        var map = {};
        for (var i = 0; i < selected_goods.length; i++) {
            var ai = selected_goods[i];
            if (ai.Goods) {
                if (!map[ai.Goods.id]) {
                    tempDate.push({
                        "goods_id": ai.Goods.id,
                        "activity_id": ai.Cart.activity_id ? ai.Cart.activity_id : 0
                    });
                }
            }
        }
        var param = {
            'user_id': id,
            "goods_array": tempDate
        };
        send_ajax('post', '/api/coupon/available', param, function (data) {
            var html = "";
            if (data.code == 200 && data.data.length) {
                var data = data.data;
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        html += '\n<option value="" data-id="' + data[i].id + '">' + data[i].name + '</option>\n                    ';
                    }
                }

                $('#coupon').append(html);
            } else {}
        });
    };
    //提交订单
    $('.sum_order').click(function () {
        if (!id) {
            if (shopAddress) {
                var addrParam = shopAddress.UserAddress;
            } else {
                alert('请选择收货地址！');
                return;
            }
        };

        var addrId = $('.getAddrParam').attr('data-address_id');
        var note_msg = $('.remarks_information').val();
        var use_point = $('.input_number').val();
        var coupon = $('#coupon').find("option:checked").attr("data-id");
        if (coupon == undefined) {
            coupon = 0;
        }
        //会员日id
        var memberId;
        var myDate = new Date();
        var day = myDate.getDate();
        var member_id = {
            "MemberDay": {
                "day": day
                //获取会员日的id
            }
        };
        send_ajax('post', '/get', member_id, function (data) {
            if (data.code == 200) {
                if (data.MemberDay) {
                    memberId = data.MemberDay.id;
                }
            }
        });
        var params;
        var tempDate = []; //调教订单商品数据
        var map = {};
        var subGoodsIs = [];
        if (selected_goods.length) {
            for (var i = 0; i < selected_goods.length; i++) {
                var ai = selected_goods[i];
                if (!map[ai.Goods.id]) {
                    tempDate.push({
                        "goodsId": ai.Goods.id,
                        "count": ai.Goods.count
                    });
                }
            }
        } else if (goodsList.length) {
            for (var i = 0; i < goodsList.length; i++) {
                var ai = goodsList[i];
                if (ai.selected_flag) {
                    subGoodsIs.push(ai.id);
                    if (!map[ai.id]) {
                        tempDate.push({
                            "goodsId": ai.id,
                            "count": 0
                        });
                    }
                }
            }
        }
        //选择的付款方式
        //cod_flag = 1是选择货到付款
        //cod_flag = 0是选择其他的付款方式
        var cod_flag = 0;
        var pay_way = $('.pay_way .payment_m');
        for (var i = 0; i < pay_way.length; i++) {
            if ($(pay_way[i]).hasClass('open')) {
                if ($(pay_way[i]).attr('data-id') == 1) {
                    cod_flag = 1;
                } else {
                    cod_flag = 0;
                }
            }
        };
        params = {
            'userId': id ? id : 0,
            // 'coupon_id': coupon,
            // 'point': use_point ? use_point : 0,
            'goodsList': tempDate,
            // 'cod_flag': cod_flag,
            "note": note_msg,
            "addressId": addrId ? addrId : 0,
            // "city": id ? userCity : addrParam.city,
            // "location": id ? userLocation : addrParam.location,
            // "district": id ? userDistrict : addrParam.district,
            // "province": id ? userProvince : addrParam.province,
            // "street": id ? userStreet : addrParam.street,
            // "memberId": memberId ? memberId : '',
            // "receiver_name":userReceiver ,
            // "receiver_phone": userPhone
        };
        //提交订单
        send_ajax('post', '/api/order/goods_submit', params, function (data) {
            if (data.code == 200) {
                var result = data.data;
                if (!id) {
                    for (var k = 0; k < goodsList.length; k++) {
                        for (var n = 0; n < subGoodsIs.length; n++) {
                            if (goodsList[k].id == subGoodsIs[n]) {
                                goodsList.splice(k, 1);
                            }
                        }
                    };
                    localStorage.setItem("noUsers", JSON.stringify(goodsList));
                }
                if (cod_flag) {
                    alert('订单提交成功');
                    window.location.href = "/user/order_details.html?order_sn=" + result;
                } else {
                    window.location.href = "/goods/order_payment.html?order_sn=" + result;
                }
            }
        });
    });
    //送优惠券
    function sendCoupon() {
        var params = {
            "CartCoupon": {
                "user_id": id
            }
        };
        send_ajax('post', '/head', params, function (data) {
            if (data.code == 200) {
                $('.coupon_number').text(data.CartCoupon.count);
            }
        });
    };
    //四舍五入
    function keepTwoDecimalFull(num) {
        var result = parseFloat(num);

        if (isNaN(result)) {
            alert('传递参数错误，请检查！');
            return false;
        }

        result = Math.round(num * 100) / 100;

        var s_x = result.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0';
        }
        return s_x;
    };
   
});